package com.woniuxy.yuekeuser.controller;
import com.woniuxy.yuekeuser.common.Result;
import com.woniuxy.yuekeuser.controller.Info.UserLoginInfo;
import com.woniuxy.yuekeuser.dao.UserMapper;
import com.woniuxy.yuekeuser.info.UserInfo;
import com.woniuxy.yuekeuser.model.User;
import com.woniuxy.yuekeuser.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniuxy.yuekeuser.model.Income;
import com.woniuxy.yuekeuser.model.Order;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;

import persion.zhc.tool.SMSVerificationAPI;
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Freedom
 * @since 2020-11-03
 */
@Slf4j
@CrossOrigin("*")
@RestController
public class UserController {
    @Autowired
   private IUserService userService;
//    @Autowired
//    private UserMapper userMapper;

    //用户个人资料信息
    @PostMapping("user/message")
    public Result userMassage(HttpSession session){
        log.info("获取用户信息请求成功");
        //从session中获取当前用户
        UserInfo user=null;
        Object obj=session.getAttribute("User");
        if(obj instanceof UserInfo){
           user=(UserInfo) obj;
        }
        else {
            //如果为空则抛异常
           // handleException(Exception e);
        }
       // User user=userMapper.selectById(1);
        log.info("获取到的数据为{}",user);
        return Result.success(user);
    }

    //修改信息
    @PostMapping("user/modifyMassage")
    public Result modifyUserMassage(@RequestParam("file")MultipartFile file, User user){
        //获取图片存到指定位置并将地址保存到User当中

        String fileName = file.getOriginalFilename();
        String filePath = "/Users/itinypocket/workspace/temp/";
        String address=fileName+filePath;
        File dest = new File(address);
        try {
            file.transferTo(dest);
            log.info("图片上传成功");
        } catch (IOException e) {

        }
        //将图片存入到User中
        String str=null;
        if(user==null){

        }else {
            user.setHeadPortraitAddress(address);
            str=userService.modifyMassage(user);
        }
        return Result.success(str);
    }
//展示用户的所有的订单页面
    @PostMapping("user/useRACount")
    public Result UserCount(HttpSession session,String orderState,@RequestParam(defaultValue = "1") int currentPage,
                            @RequestParam(defaultValue = "5") int pageSize){
        Object obj=session.getAttribute("User");
        UserInfo user=null;
        if(obj instanceof User){
           user=(UserInfo) obj;
        }
        else {
            return Result.fail("数据异常");
        }
        Page<Income> page=new Page<>(currentPage,pageSize);
        IPage<Income> p=userService.getUserIncome(page,user.getUserId());
        return Result.success(p);

    }
//展示用户的所有消费记录
    @GetMapping("/user/userOrder")
    public Result getIncome(HttpSession session,@RequestParam(defaultValue = "1") int currentPage,
                            @RequestParam(defaultValue ="5") int pageSize,String state){
        Object obj=session.getAttribute("User");
        UserInfo user=null;
        if(obj instanceof UserInfo){
            user=(UserInfo)obj;
        }
        else {
            return Result.fail("数据异常");
        }
        log.info("当前页数：{}",currentPage);
        log.info("获取到的当前用户所有订单的的订单状态{}",state);
        Page<Order> page=new Page<>();
        page.setSize(pageSize);
        page.setCurrent(currentPage);
        log.info("page里的数据{}",page.getCurrent(),page.getSize());
        IPage<Order> ipage=userService.getUserOrder(page,user.getUserId(),state);

        return Result.success(ipage);
    }



    @Autowired
    private SMSVerificationAPI smsVerificationAPI;

    @Autowired
    private IUserService iUserService;


    /**
     * @MethodName userRegister
     * @Description
     * @Author Cheney
     * @Date 2020/11/3 11:34
     **/
    @PostMapping("user/register")
    public Result userRegister(User user){

//        String SMSCode = (String)session.getAttribute("SMSCode");
//        log.info("用户注册请求发送成功！参数，用户user为{},输入验证码{}。该用户的验证码为{}",user,SMSCode1,SMSCode);
//
//
//        if(SMSCode == null){
//            return Result.fail("验证码已过期！");
//        }
//
//        if(!SMSCode.equals(SMSCode1)){
//            return Result.fail("验证码错误");
//        }
//
//        session.removeAttribute("SMSCode");
        return iUserService.userRegister(user) ?Result.success():Result.fail("账号已存在！");

    }

    /**
     * @MethodName getSMSCode
     * @Description 用户注册获取验证码，返回一个验证码字符串到前端。需要前端发送参数为：用户名和电话
     * @Author Cheney
     * @Date 2020/11/3 10:13
     **/
    @GetMapping("user/getSMSCode")
    public Result getSMSCode(HttpSession session,String tel){

        log.info("用户验证码请求成功，参数用电话为：{}",tel);

        UserInfo user = iUserService.userLoginSMS(tel);
        if(user ==null){
            return Result.fail("用户不存在");
        }

        if(user.getStatus().equals("封禁")){
            return Result.fail("账号已被封禁，请联系管理员！");
        }

        Map<String,String> map = new HashMap<>();

        String SMSCode = String.valueOf((int)(Math.random()*10000));
        session.setAttribute("SMSCode",SMSCode);
        log.info("验证码生成成功！值为：{}",SMSCode);

        //5分钟后删除验证码，验证码失效
        final Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                session.removeAttribute("SMSCode");
                log.info(user.getName()+"，验证码失效");
                timer.cancel();
            }
        },5*60*1000);

        map.put("mobile",tel);
        map.put("params",user.getName()+","+SMSCode);

        String result = smsVerificationAPI.SMSVerification(map);

        if(result.contains("\"result\":0")){

            return Result.success();
        }

        if(result.contains("\"result\":1016")){
            return Result.fail("手机号格式错误!");
        }

        return Result.fail("未知错误！");

    }

    /**
     * @MethodName userLogin
     * @Description 用户登录，userLoginInfo中的loginMethod为空则为密码方式登录，若不为空则为短信登录
     * @Author Cheney
     * @Date 2020/11/3 14:26
     **/
    @PostMapping("user/login")
    public Result userLogin(UserLoginInfo userLoginInfo,HttpSession session){

        log.info("用户登录请求成功！请求参数为{},session为{}",userLoginInfo,session);

        String SMSCode = (String) session.getAttribute("SMSCode");


        if(!userLoginInfo.getLoginMethod().equals("normal")){
            log.info("用户以短信验证码方式登录！");
            if(userLoginInfo.getSMSCode().equals(SMSCode)){
                UserInfo user2 = iUserService.userLoginSMS(userLoginInfo.getUserTel());
                session.setAttribute("User",user2);
                log.info("用户短信验证码登录成功");
                session.removeAttribute("SMSCode");
                return Result.success(user2);
            }else {
                return Result.fail("验证码错误，登录失败");
            }
        }else {
            log.info("用户以账号密码方式登录！");
            UserInfo user = iUserService.userLogin(userLoginInfo.getUserTel(),userLoginInfo.getPassword());
            if(user!= null && user.getStatus().equals("正常")){
                session.setAttribute("User",user);
                log.info("用户登录成功");
                return Result.success(user);
            }if(user!= null && user.getStatus().equals("封禁")){
                log.info("用户登录失败，账户已被封禁");
                return Result.fail("账号已被封禁，请联系管理员！");
            }else
                return Result.fail("账号或密码错误！");
        }
    }

    @PostMapping("user/loginOut")
    public Result loginOut(HttpSession session){
        log.info("用户请求登出");

        session.removeAttribute("User");

        return Result.success();
    }

    @GetMapping("user/getMyStatus")
    public Result getMyStatus(HttpSession session){

        if(session.getAttribute("User")!=null){

            return Result.success(session.getAttribute("User"));
        }else {
            return Result.fail("登录已失效");
        }
    }

//    @GetMapping("user/getMyStatus")
//    public Result getMyStatus(HttpSession session){
//
//        if(session.getAttribute("User")!=null){
//            return Result.success();
//        }else {
//            return Result.fail("请重新登录");
//        }
//    }
}

